import MDEditor from '@uiw/react-md-editor'
import { useState, useEffect } from 'react'
import { useParams, useHistory } from 'react-router-dom'
import Loading from '../Loading'
import styles from './Update.module.css'
import { BASE_URL } from '../../constants'
const Update = () => {
  const { id } = useParams()
  const history = useHistory()
  const [ content, setContent ] = useState('')
  const [ title , setTitle ] = useState('')
  const [ category , setCategory ] = useState('')
  useEffect(() => {
    fetch(`${BASE_URL}/articles/`+id)
    .then(res => res.json())
    .then(res => {
      setTitle(res.title)
      setContent(res.content)
      setCategory(res.category)
    })
  },[id])
  const handleClick = () => {
    if (title.trim() === "") {
      alert("标题不能为空!")
      return
    }
    if (content.trim() === "") {
      alert("内容不能为空!")
      return
    }
    if (category.trim() === "") {
      alert("分类不能为空!")
      return
    }
    const fd = new FormData()
    fd.append('title', title)
    fd.append('content', content)
    fd.append('category', category)
    fetch(`${BASE_URL}/articles/`+id, {
      method: "PUT",
      body: fd
    })
    .then(res => res.json())
    .then(res => {
      if (res.status !== 'ok') alert('更新失败')
      else {
        alert('修改成功')
        history.push("/")
      }
    })
  }
  return (
    <div className={styles.update}>
      { !title && <Loading /> }
      {
        title &&
        (
          <>
            <div className={styles.title}>
              <span>修改文章</span>
              <button onClick={() => handleClick()}>发布</button>
            </div>
            <div>
              <div className={styles.formControl}>
                <label>标题</label>
                <input type="text" value={title} onChange={(e) => setTitle(e.target.value)}/>
              </div>
              <div className={styles.formControl}>
                <label>分类</label>
                <input type="text" value={category} onChange={e => setCategory(e.target.value)}/>
              </div>
              <MDEditor
                value={content}
                onChange={setContent}
              />
            </div>
          </>
        )
      }
    </div>
  )
}

export default Update